/**
 * 
 */
package org.framework2.test.webserver.http;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.framework2.test.webserver.http.request.WSTMHttpRequest;
import org.framework2.test.webserver.http.response.WSTMHttpResponse;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * 脚本引擎适配请求处理器
 * @author ahli
 */
public class WSTMHttpRequestHandler implements HttpHandler {

	/**
	 * 日志对象
	 */
	private static final Log log = LogFactory.getLog(WSTMHttpRequestHandler.class);
	
	/**
	 * Servlet
	 */
	private WSTMHttpServlet servlet;
	
	public WSTMHttpServlet getServlet() {
		return servlet;
	}

	public void setServlet(WSTMHttpServlet servlet) {
		this.servlet = servlet;
	}

	/* (non-Javadoc)
	 * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
	 */
	@Override
	public void handle(HttpExchange arg0) throws IOException {
		// 读取请求体输入流
		if(log.isDebugEnabled()){
			Headers headers = arg0.getRequestHeaders();
			log.debug("Headers: { " + headers.entrySet() + "}");
		}
		
		WSTMHttpRequest request = new WSTMHttpRequest(arg0);
		WSTMHttpResponse response = new WSTMHttpResponse(arg0);
		
		// 设置HTTP回执的状态
		arg0.sendResponseHeaders(response.getStatus(), 0);
		
		// 设置返回字符集
		Headers headers = arg0.getResponseHeaders();
		headers.set("Content-Type", "text/html; charset=UTF-8");
		headers.set("contentType", "application/xml");
		try {
			servlet.execute(request, response);
		} catch (IOException e) {
			log.error(e.toString());
			throw e;
		} catch (Exception e) {
			log.error(e.toString());
			e.printStackTrace();
		} finally{
			OutputStream os = arg0.getResponseBody();
			if(null != os ){
				try{
					os.flush();
					os.close();
				}catch(IOException e){
					log.debug(e.toString());
				}
			}
			
			arg0.close();
		}
	}
}
